package com.cosw.util;

public class TLVTools {
	public static short setLength(byte[] buff, short off, short len) {
		if (len < 0x80) {
			buff[off++] = (byte) len;
		} else if (len >= 0x80 && len < 0x100) {
			buff[off++] = (byte) 0x81;
			buff[off++] = (byte) len;
		} else {
			buff[off++] = (byte) 0x82;
			buff[off++] = (byte) ((len >> (byte) 0x08) & (byte) 0xFF);
			buff[off++] = (byte) (len & (byte) 0xFF);
		}

		return off;
	}

	/**
	 * 
	 * @param tlvBuff
	 *            T 7X T 81 XX T 82 XX XX;
	 * @param off
	 * @return
	 */
	public static short getValueLength(byte[] tlvBuff, short off) {
		if (tlvBuff[(short) (off + 1)] == (byte) 0x81) {
			return StringUtil.byte2Short(tlvBuff[(short) (off + 2)]);
		} else if (tlvBuff[(short) (off + 1)] == (byte) 0x82) {
			return (short) (StringUtil.byte2Short(tlvBuff[(short) (off + 2)]) * 0x100 + StringUtil
					.byte2Short(tlvBuff[(short) (off + 3)]));
		} else {
			return tlvBuff[(short) (off + 1)];
		}
	}

	public static byte getTLWidth(byte[] tlvBuff, short off) {
		if (tlvBuff[(short) (off + 1)] == (byte) 0x81) {
			return (byte) 0x03;
		} else if (tlvBuff[(short) (off + 1)] == (byte) 0x82) {
			return (byte) 0x04;
		} else {
			return (byte) 0x02;
		}
	}

	public static short appendLV(byte[] s, short s_off, short s_len, byte[] t,
			short t_off) {

		t_off = setLength(t, t_off, s_len);
		StringUtil.byteArrayCopy(s, s_off, t, t_off, s_len);
		t_off += s_len;

		return t_off;
	}

	public static short appendTLV(byte tag, byte[] s, short s_off, short s_len,
			byte[] t, short t_off) {

		t[t_off++] = tag;
		t_off = setLength(t, t_off, s_len);
		StringUtil.byteArrayCopy(s, s_off, t, t_off, s_len);
		t_off += s_len;

		return t_off;
	}

}
